#include "stdafx.h"
#include "../core/Exception.h"
#include "utf8.h"
#include "../core/Convert.hpp"

namespace ja2
{
	std::int_least32_t Convert::string_to_int32(std::string const &Value)
	{
		static_assert(sizeof(std::uint_least32_t) >= sizeof(unsigned long), __FUNCTION__ " - unsigned long is larger than std::uint_least32_t");
		char *p_end;
		unsigned long const number = strtoul(Value.c_str(), &p_end, 10);
		// No conversion occurs
		if(Value.c_str() == p_end || errno == ERANGE)
			throw std::runtime_error(std::string("Cannot convert '") + Value + "' to number.");

		return number;
	}

	std::wstring Convert::to_utf16(std::string const &Str)
	{
		std::wstring out;
		try
		{
			utf8::utf8to16(Str.begin(), Str.end(), std::back_inserter(out));
		}
		catch(utf8::invalid_utf8 const &e)
		{
			throw InvalidUtf8((boost::format("%1%: %X") % e.what() % e.utf8_octet()).str());
		}

		return out;
	}

	std::string Convert::to_utf8(std::wstring const &Str)
	{
		std::string out;
		utf8::utf16to8(Str.begin(), Str.end(), std::back_inserter(out));
		return out;
	}
} /*ja2*/